package com.x.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jodd.mail.Email;
import jodd.mail.SendMailSession;
import jodd.mail.SmtpServer;

/**
 * <p>
 * Description:邮件工具
 * </p>
 * 
 * @Author Chenkangming
 * @Date 2015-11-09
 * @version 1.0
 */
public class MailUtil {

	private static Logger log = LoggerFactory.getLogger(MailUtil.class);

	/**
	 * 发送邮件(纯文本内容)
	 * 
	 * @param from
	 *            发件人昵称
	 * @param username
	 *            发件人邮箱地址
	 * @param password
	 *            发件人邮箱密码
	 * @param smtp
	 *            smtp
	 * @param to
	 *            接收人地址
	 * @param title
	 *            邮件标题
	 * @param text
	 *            邮件文本内容
	 * @return
	 */
	public static boolean send(String from, String username, String password, String smtp, String to, String title, String text) {
		boolean sendResult = true;
		SendMailSession session = null;
		try {
			Email email = Email.create().from(from).to(to).subject(title).addText(text);
			SmtpServer<?> smtpServer = SmtpServer.create(smtp).authenticateWith(username, password);
			session = smtpServer.createSession();
			session.open();
			String result = session.sendMail(email);
			log.info(result);
		} catch (Exception e) {
			log.error("{}", e);
			sendResult = false;
		} finally {
			if (session != null) {
				session.close();
			}
		}
		return sendResult;
	}

	/**
	 * 发送邮件(发送html格式内容)
	 * 
	 * @param from
	 *            发件人昵称
	 * @param username
	 *            发件人邮箱地址
	 * @param password
	 *            发件人邮箱密码
	 * @param smtp
	 *            smtp
	 * @param to
	 *            接收人地址
	 * @param title
	 *            邮件标题
	 * @param html
	 *            邮件html内容
	 * @return true/false
	 */
	public static boolean sendHtml(String from, String username, String password, String smtp, String to, String title, String html) {
		boolean sendResult = true;
		SendMailSession session = null;
		try {
			Email email = Email.create().from(from).to(to).subject(title).addHtml(html);
			SmtpServer<?> smtpServer = SmtpServer.create(smtp).authenticateWith(username, password);
			session = smtpServer.createSession();
			session.open();
			String result = session.sendMail(email);
			log.info(result);
		} catch (Exception e) {
			log.error("{}", e);
			sendResult = false;
		} finally {
			if (session != null) {
				session.close();
			}
		}
		return sendResult;
	}

}
